import { NextFunction, Request, Response } from "express";
import { User } from "../interfaces/user.interface";
import userService from "../services/user.services";
/* eslint-disable */
const jwt = require('jsonwebtoken')
import {
	generateSignToken,
	TokenSecretKey,
	TokenExpired,
	RefreshTokenExpired,
	sendMsg,
	checkSignToken,
	RetCodeMap,
} from "../utils/util";
const secretKey = "kkk *_*"
import md5 from "md5";
class UsersController {
	public UserService = new userService();
	public login = async (req: Request, res: Response, next: NextFunction) => {
		try {
			console.log(req.body);
			const { username, password } = req.body as any;
			const findData: User | null = await this.UserService.findUserByUsername(
				username
			);
			if (findData && findData.password === md5(password)) {
				const jwtToken = generateSignToken(
					{
						id: findData.id,
						username,
					},
					TokenSecretKey,
					TokenExpired
				);
				const refreshToken = generateSignToken(
					{ id: findData.id, username },
					TokenSecretKey,
					RefreshTokenExpired
				);
				const tokenStr = jwt.sign({username: req.body.username}, secretKey, {expiresIn: "24h"})
				sendMsg({
					res,
					data: {
						jwtToken,
						refreshToken,
						username: findData.username,
						token: tokenStr
					},
					message: "登陆成功，用户名为${findData.username}",
				})
			}
		} catch (error) {
			next(error);
		}
	};
	public register = async (req: Request, res: Response, next: NextFunction) => {
		try {
			const { Action, ...Data }: any = req.body || {};
			if (!Data || !Data.username || !Data.password) {
				res.status(200).json({ RetCode: 1, Message: `注册用户信息错误！` });
				return;
			}

			Data.password = md5(Data.password);
			const createData: User = await this.UserService.createUser(Data);
			res
				.status(200)
				.json({ retCode: 0, data: {}, Message: "注册新用户成功!" });
		} catch (error) {
			console.log(error);
			next(error);
		}
	};
	public userlist = async (req: Request, res: Response, next: NextFunction) => {
		console.log('请求过来饿了')
		let params = req.query as any;
		params.limit = Number(params.limit || 10);
		params.offset = (params.page - 1 || 0) * params.limit;
		console.log(params)
		const { count = 0, Data = [] } = await this.UserService.findAndCountAll({
			...params,
			attributes: { exclude: ["password"] },
			where: {
				// 当username存在时进行精确匹配，不存在时匹配所有用户
				...params.username && { username: params.username },
				...params.ruleId && { username: params.ruleId },
			},
		});
		res.status(200).json({
			retCode: 0,
			data: {
				count,
				list: Data,
			},
			message: "请求成功",
		});
	};
	public userDetail = async (req: Request, res: Response, next: NextFunction) => {
		try {
			const { id } = req.query as any;
			if (!id) {
				sendMsg({ res, retCode: 1, message: `请求参数错误！` });
				return;
			}
			const findData: User | null = await this.UserService.findUserById(Number(id));	
			sendMsg({ res, message: `请求成功`, data: findData  });
		} catch (error) {
			next(error);
		}
	}
}
export default UsersController;
